<?php

class Aliyun_ocr_service extends BASE_Service {

    public function __construct() {
        parent::__construct();

        $this->load->model("api_log_model");

        $this->_config = config_item("aliyun");
    }

    public function shibieShenfenzhengFace($image_url) {

        $param = [
            "Action" => "RecognizeIdcard",
            "Url" => $image_url,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["ocr"]["api_url"], $param, "识别身份证正面");

        $truename = "";
        $sex = "";
        $id_card = "";

        if ($result["status_code"] == 1) {
            if (isset($result["data"]["data"]["face"]["data"])) {
                $data = $result["data"]["data"]["face"]["data"];
                if (isset($data["name"])) {
                    $truename = $data["name"];
                }
                if (isset($data["sex"])) {
                    $sex = $data["sex"];
                }
                if (isset($data["idNumber"])) {
                    $id_card = $data["idNumber"];
                }
            }
        }

        return [
            "truename" => $truename,
            "sex_name" => $sex,
            "sex" => $sex == "男" ? 1 : ($sex == "女" ? 2 : ""),
            "id_card" => $id_card,
        ];
    }

    public function shibieShenfenzhengBack($image_url) {

        $param = [
            "Action" => "RecognizeIdcard",
            "Url" => $image_url,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["ocr"]["api_url"], $param, "识别身份证反面");

        $issueAuthority = "";
        $id_card_start = "";
        $id_card_end = "";

        if ($result["status_code"] == 1) {
            if (isset($result["data"]["data"]["back"]["data"])) {
                $data = $result["data"]["data"]["back"]["data"];
                if (isset($data["issueAuthority"])) {
                    $issueAuthority = $data["issueAuthority"];
                }
                if (isset($data["validPeriod"])) {
                    $validPeriod = $data["validPeriod"];
                    $id_card_arr = explode("-", $validPeriod);
                    $id_card_start = $id_card_arr[0];
                    $id_card_end = $id_card_arr[1];
                }
            }
        }

        return [
            //"issueAuthority" => $issueAuthority,
            "id_card_start" => str_replace(".", "-", $id_card_start),
            "id_card_end" => str_replace(".", "-", $id_card_end),
        ];
    }

    public function shibieJiashizhengFace($image_url) {

        $param = [
            "Action" => "RecognizeDrivingLicense",
            "Url" => $image_url,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["ocr"]["api_url"], $param, "识别驾驶证");

        $driver_license_no = "";
        $driver_license_start = "";
        $driver_license_end = "";
        $driver_license_type = "";
        $driver_license_type_name = "";
        $driver_issue_authority = "";

        if ($result["status_code"] == 1) {
            if (isset($result["data"]["data"]["face"]["data"])) {
                $data = $result["data"]["data"]["face"]["data"];
                if (isset($data["licenseNumber"])) {
                    $driver_license_no = $data["licenseNumber"];
                }
                if (isset($data["validPeriod"])) {
                    $validPeriod = $data["validPeriod"];
                    $driver_license_arr = explode("至", $validPeriod);
                    $driver_license_start = $driver_license_arr[0];
                    $driver_license_end = $driver_license_arr[1];
                }
                if (isset($data["approvedType"])) {
                    $driver_license_type_name = $data["approvedType"];
                }
                if (isset($data["issueAuthority"])) {
                    $driver_issue_authority = $data["issueAuthority"];
                }
            }
        }
        if ($driver_license_type_name != "") {
            $this->load->model("zidian_model");
            $zidian = $this->zidian_model->getData("where type_id=1 and code='" . $driver_license_type_name . "'", 1, 1, "");
            if (!empty($zidian)) {
                $driver_license_type = $zidian[0]["id"];
            } else {
                $driver_license_type_name = "";
            }
        }

        return [
            "driver_license_no" => $driver_license_no,
            "driver_license_start" => str_replace(".", "-", $driver_license_start),
            "driver_license_end" => str_replace(".", "-", $driver_license_end),
            "driver_license_type" => $driver_license_type,
            "driver_license_type_name" => $driver_license_type_name,
            "driver_issue_authority" => $driver_issue_authority,
        ];
    }

    public function shibieXingshizhengFace($image_url) {

        $param = [
            "Action" => "RecognizeVehicleLicense",
            "Url" => $image_url,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["ocr"]["api_url"], $param, "识别行驶证正页");

        $car_number = "";
        $xingshizheng_owner = "";
        $user_nature = "";
        $xingshizheng_register_date = "";
        $xingshizheng_lingzheng_date = "";
        $xingshizheng_fazheng_jiguan = "";
        $xingshizheng_vehicle_type_name = "";
        $xingshizheng_vehicle_type = 0;

        if ($result["status_code"] == 1) {
            if (isset($result["data"]["data"]["face"]["data"])) {
                $data = $result["data"]["data"]["face"]["data"];
                if (isset($data["licensePlateNumber"])) {
                    $car_number = $data["licensePlateNumber"];
                }
                if (isset($data["owner"])) {
                    $xingshizheng_owner = $data["owner"];
                }
                if (isset($data["useNature"])) {
                    $user_nature = $data["useNature"];
                }
                if (isset($data["registrationDate"])) {
                    $xingshizheng_register_date = $data["registrationDate"];
                }
                if (isset($data["issueDate"])) {
                    $xingshizheng_lingzheng_date = $data["issueDate"];
                }
                if (isset($data["issueAuthority"])) {
                    $xingshizheng_fazheng_jiguan = $data["issueAuthority"];
                }
                if (isset($data["vehicleType"])) {
                    $xingshizheng_vehicle_type_name = $data["vehicleType"];
                }
            }
        }
        if ($xingshizheng_vehicle_type_name != "") {
            $this->load->model("zidian_model");
            $zidian = $this->zidian_model->getData("where type_id=33 and name='" . $xingshizheng_vehicle_type_name . "'", 1, 1, "");
            if (!empty($zidian)) {
                $xingshizheng_vehicle_type = $zidian[0]["id"];
            }
        }


        return [
            "car_number" => $car_number,
            "xingshizheng_owner" => $xingshizheng_owner,
            "user_nature" => $user_nature,
            "xingshizheng_register_date" => str_replace(".", "-", $xingshizheng_register_date),
            "xingshizheng_lingzheng_date" => str_replace(".", "-", $xingshizheng_lingzheng_date),
            "xingshizheng_fazheng_jiguan" => $xingshizheng_fazheng_jiguan,
            "xingshizheng_vehicle_type" => $xingshizheng_vehicle_type,
            "xingshizheng_vehicle_type_name" => $xingshizheng_vehicle_type_name,
        ];
    }

    public function shibieXingshizhengBack($image_url) {

        $param = [
            "Action" => "RecognizeVehicleLicense",
            "Url" => $image_url,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["ocr"]["api_url"], $param, "识别行驶证副页");

        $xingshizheng_sn = "";
        $chezhong = 0;
        $zaizhong = 0; //核载
        $zhengbei = 0; //整备

        if ($result["status_code"] == 1) {
            if (isset($result["data"]["data"]["back"]["data"])) {
                $data = $result["data"]["data"]["back"]["data"];
                if (isset($data["barcodeNumber"])) {
                    $xingshizheng_sn = $data["barcodeNumber"];
                }
                if (isset($data["curbWeight"])) {//整备
                    $zhengbei = intval($data["curbWeight"]) ? intval($data["curbWeight"]) / 1000 : 0;
                }
                if (isset($data["permittedWeight"])) {//核载
                    if (floatval($data["permittedWeight"]) > 0) {
                        $zaizhong = floatval($data["permittedWeight"]) / 1000;
                        $chezhong = $zhengbei + $zaizhong;
                    }
                }
                if (isset($data["tractionWeight"])) {//牵引
                    if (floatval($data["tractionWeight"]) > 0) {
                        $zaizhong = floatval($data["tractionWeight"]) / 1000;
                        $chezhong = $zhengbei + $zaizhong;
                    }
                }
                if (isset($data["totalWeight"])) {//总质量
                    if (floatval($data["totalWeight"]) > 0) {
                        $chezhong = floatval($data["totalWeight"]) / 1000;
                    }
                }
            }
        }

        return [
            "xingshizheng_sn" => $xingshizheng_sn,
            "chezhong" => $chezhong,
            "zaizhong" => $zaizhong,
        ];
    }

    public function shibieYinhangka($image_url) {

        $param = [
            "Action" => "RecognizeBankCard",
            "Url" => $image_url,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["ocr"]["api_url"], $param, "识别银行卡");

        $card_sn = "";
        $bank_id = "";
        $bank_name = "";

        if ($result["status_code"] == 1) {
            if (isset($result["data"]["data"])) {
                $data = $result["data"]["data"];
                if (isset($data["cardNumber"])) {
                    $card_sn = $data["cardNumber"];
                }
                if (isset($data["bankName"])) {
                    $bank_name = $data["bankName"];
                }
            }
        }
        if ($bank_name != "") {
            $this->load->model("zidian_model");
            $zidian = $this->zidian_model->getData("where type_id=10 and name='" . $bank_name . "'", 1, 1, "");
            if (!empty($zidian)) {
                $bank_id = $zidian[0]["id"];
            }
        }

        return [
            "card_sn" => $card_sn,
            "bank_id" => $bank_id,
            "bank_name" => $bank_name,
        ];
    }

    public function postApi($url, $params, $item) {

        $utc_time = strtotime("-8 hours");

        $paramsTmp = [
            "Version" => "2021-07-07",
            "Format" => "JSON",
            "AccessKeyId" => $this->_config["AccessKeyId"],
            "SignatureNonce" => uniqid(),
            "Timestamp" => date("Y-m-d", $utc_time) . "T" . date("H:i:s", $utc_time) . "Z",
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureVersion" => "1.0",
        ];
        $params = array_merge($paramsTmp, $params);

        $str = "";
        ksort($params);
        foreach ($params as $k => $v) {
            $str .= "&" . $k . "=" . urlencode($v);
        }
        $str = trim($str, "&");

        $Signature = $this->getSignature("GET&%2F&" . urlencode($str), $this->_config["AccessKeySecret"] . "&");

        $str .= "&Signature=" . urlencode($Signature);

        $params["Signature"] = $Signature;

        $url = $url . "/?" . $str;

        $request_data = [
            "url" => $url,
                //"params" => $params,
        ];

        $params = jsonEncode($params);

        $header = ['Content-Type:application/x-www-form-urlencoded'];

        //if (isset($this->_config["ocr"]["is_kaitong"]) && $this->_config["ocr"]["is_kaitong"] == 1) {

        $rs = $this->clientCurl($url, [], $header);

        //print_r($rs);
        $return_data = $rs["data"];

        $status_code = 0;
        $msg = "失败";
        $data = [];
        $return_code = "";

        if ($rs["code"] == 200) {
            $sys_data = jsonDecode($rs["data"]);
            if (isset($sys_data) && !empty($sys_data)) {
                if (isset($sys_data["Data"])) {
                    $real_data = jsonDecode($sys_data["Data"]);
                    if (isset($real_data) && !empty($real_data)) {
                        $status_code = 1;
                        $msg = "";
                        $data = $real_data;

                        $return_data = $rs["data"];
                    }
                } else {
                    $msg = $sys_data["Message"] . "(" . $sys_data["Code"] . ")";
                }
            } else {
                $msg = "返回数据异常";
            }
        } else {
            $msg = "接口请求异常";
        }

        //增加日志
        $this->api_log_model->addLog(1, $item, $request_data, $return_data);

        log_message('error', "阿里去OCR->" . $item . "(返回数据)=>" . is_array($return_data) ? jsonEncode($return_data) : $return_data);

        return [
            "status_code" => $status_code,
            "msg" => $msg,
            "data" => $data,
            "return_code" => $return_code,
        ];
//        } else {
//            return [
//                "status_code" => 0,
//                "msg" => "未开通ocr",
//                "data" => [],
//                "return_code" => "",
//            ];
//        }
    }

    public function clientCurl($url, $jsonData = "", $header = []) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        /*         * 配置返回信息* */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //获取的信息以文件流的形式返回，不直接输出
        curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
        /*         * 配置超时* */
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //连接前等待时间,0不等待
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //连接后等待时间,0不等待
        /*         * 配置页面重定向* */
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//跟踪爬取重定向页面
        //curl_setopt($ch, CURLOPT_MAXREDIRS, 10);//指定最多的HTTP重定向的数量
        //curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        /*         * 配置HEADER* */
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //curl_setopt($ch, CURLOPT_ENCODING, ""); // Accept-Encoding编码，支持"identity"/"deflate"/"gzip",空支持所有编码
        if (strpos(strtolower($url), 'https') !== false) {
            /*             * 禁止证书验证防止curl输出空白* */
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //禁止 cURL 验证对等证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //是否检测服务器的域名与证书上的是否一致
        }
        /*         * 配置POST* */
        //curl_setopt($ch, CURLOPT_POST, 1); //支持post提交数据
        //curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

        $code = 200; //执行成功
        $result_data = curl_exec($ch);
        if (curl_errno($ch)) {
            $code = 400; //执行异常
            $result_data = curl_error($ch);
        }
        curl_close($ch);

        return ['code' => $code, 'data' => $result_data];
    }

    function getSignature($str, $key) {
        $signature = "";
        if (function_exists('hash_hmac')) {
            $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
        } else {
            $blocksize = 64;
            $hashfunc = 'sha1';
            if (strlen($key) > $blocksize) {
                $key = pack('H*', $hashfunc($key));
            }
            $key = str_pad($key, $blocksize, chr(0x00));
            $ipad = str_repeat(chr(0x36), $blocksize);
            $opad = str_repeat(chr(0x5c), $blocksize);
            $hmac = pack(
                    'H*', $hashfunc(
                            ($key ^ $opad) . pack(
                                    'H*', $hashfunc(
                                            ($key ^ $ipad) . $str))
                    )
            );
            $signature = base64_encode($hmac);
        }
        return $signature;
    }

}
